// pages/user/bind/company.js
import {
  bindCompany,
  getCompanyBindingInfo,
  getCompanyName,
} from '../../../api/company.js';
import {
  getSubscribeMessageAuth,
  param2Obj,
  urlParam2Obj
} from '../../../utils/util.js';
import {
  removeBadge
} from '../../../api/other.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLogin: false,
    isBind: false,
    companyId: 0,
    companyName: '',
    companyInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.scene) {
      let scene = param2Obj(decodeURIComponent(options.scene));
      this.data.companyId = Number(scene.companyId);
      //this.data.companyId = 1;

      this.slientLogin();

      getCompanyName(this.data.companyId).then(res => {

        this.setData({
          companyName: res.name
        })
      })
    } else {
      getCompanyBindingInfo().then(res => {
        this.setData({
          isBind: res.id !== 0,
          companyInfo: res,
          companyName: res.name,
          companyId: res.id,
        })
        // 消除红点
        if (getApp().globalData.unRead.company.length > 0) {
          removeBadge(5, getApp().globalData.unRead.company[0]);
          getApp().globalData.unRead.company.length = 0;
        }
      })
    }
  },

  /**
   * 绑定公司
   */
  handleBindCompany() {
    // 申请审核状态通知
    if (this.data.isLogin) {
      getSubscribeMessageAuth(['u2ia6xpt2JcK-JH9GdHlI10IjCoisDXfOJI872vajuk']).then(() => {
        bindCompany(this.data.companyId).then(() => {
          wx.showToast({
            title: '已提交绑定申请',
          })
        })
      })
    } else {
      wx.redirectTo({
        url: '/pages/login/accredit/accredit?companyId=' + this.data.companyId,
      })
    }
  },

  /**
   * 静默登录
   */
  slientLogin() {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框

          // 静默登录
          wx.login({
            success: res => {
              let code = res.code;

              wx.getUserInfo({
                success: res => {
                  // console.log(res)
                  // 可以将 res 发送给后台解码出 unionId
                  this.globalData.userInfo = res.userInfo

                  // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                  // 所以此处加入 callback 以防止这种情况
                  if (this.userInfoReadyCallback) {
                    this.userInfoReadyCallback(res)
                  }

                  // 静默登录
                  login({
                    code,
                    iv: res.iv,
                    encryptedData: res.encryptedData
                  }).then(res => {
                    getApp().globalData.isLogin = true;
                    getApp().globalData.token = res.token;
                    getApp().globalData.memberId = res.id;
                    getApp().globalData.openid = res.openId;
                    Object.assign(this.globalData.userInfo, res);
                    this.setData({
                      isLogin: true
                    })
                  }).catch(err => {
                    getApp().globalData.isLogin = false;
                  })
                }
              })
            }
          })
        }
      }
    })
  },

  /**
   * 跳转解绑页面
   */
  handleNavigatorUnbind() {
    // 申请账号解绑通知
    getSubscribeMessageAuth(['c-VZX4bMzxq3E-hb1ndenNLXhHgF22I9teWIu-b1OTw']).then(() => {
      wx.navigateTo({
        url: './unbind/index',
      })
    })
  },

  /**
   * 扫码
   */
  handleScanCode() {
    // 只允许从相机扫码
    const that = this;
    wx.scanCode({
      onlyFromCamera: true,
      success(res) {
        const {
          scene
        } = urlParam2Obj(decodeURIComponent(res.path));
        that.data.companyId = param2Obj(scene).companyId;
        getCompanyName(that.data.companyId).then(res => {
          that.setData({
            companyName: res.name
          })
        })
      }
    })
  },

})